<?php
class DbQuery extends Model
{
    public function addRecordQuery($table_name, array $data)
    {
        $table_name = DB_PREFIX . $table_name;
    
        $fields = array_keys($data);
        $values = array_values($data);
        
        foreach ($fields as $key => $field) {
            $fields[$key] = '`' . $this->db->escape($field) . '`';
            
            $values[$key] = '"' . $this->db->escape($values[$key]) . '"';
        }
        
        $fieldList = implode(', ', $fields);
        $valueList = implode(', ', $values);
        
        $sql = "INSERT INTO `$table_name` ($fieldList) VALUES ($valueList)";

        return $sql;
    }

    public function updateRecordQuery($table_name, array $data, $where)
    {
        $table_name = DB_PREFIX . $table_name;
    
        $fields = array_keys($data);
        $values = array_values($data);
        $tmp = array();
         
        foreach ($fields as $key => $field) {
            $tmp[] = '`' . $this->db->escape($field) . '` = "' . $this->db->escape($values[$key]) . '"';
        }
        $fieldList = implode(', ', $tmp);
        
        $where = $this->db->escape($where);
        
        $sql = "UPDATE `$table_name` SET $fieldList WHERE $where";

        return $sql;
    }

    public function deleteRecordQuery($table_name, $where = null, array $data = array())
    {
        $table_name = DB_PREFIX . $table_name;
    
        $sql = null;
    
        if (!empty($where)) {
            $where = $this->db->escape($where);
        
            $sql = "DELETE FROM `$table_name` WHERE $where";
        } elseif (!empty($data)) {
            $fields = array_keys($data);
            $values = array_values($data);
            $tmp = array();
            
            foreach ($fields as $key => $field) {
                $tmp[] = '`' . $this->db->escape($field) . '` = "' . $this->db->escape($values[$key]) . '"';
            }
            
            $fieldList = implode(' AND ', $tmp);
            
            $sql = "DELETE FROM `$table_name` WHERE $fieldList";
        }

        return $sql;
    }

    public function getFoundRowsQuery()
    {
        return "SELECT FOUND_ROWS() AS cnt";
    }
}